let heartbeatIntervalCache = {};
let heartbeatTimeoutCache = {};
let userlistIntervalCache = {}

/**
 * 消息中转
 */
module.exports = function handlerSocket(option) {
  /**
   * socket：当前socket对象 发送消息的那个socket
   * socketPool：存放了所有的socket对象
   * userID：当前的用户ID
   * disconnectFn：销毁函数
   * callback：除了销毁函数外所有回调都可以使用 设置参数1通过Switch使用参数2的对象
   */
  const { socket, socketPool, userID, disconnectFn, callback } = option;
  const { nsp } = socketPool[userID];
  socket.emit('online', 1)
  socket.on('typing', (data) => {
    const { to } = JSON.parse(data);
    if (socketPool[to] && socketPool[to].socket) {
      socketPool[to].socket.emit('typingreceive', data)
    }
  })
  socket.on('disconnect', function () {
    disconnectFn(userID)
  });
  socket.on('online', (falg) => {
    if (!heartbeatIntervalCache[userID]) {
      heartbeatIntervalCache[userID] = setInterval(() => {
        console.log(`初始化${userID}的定时器`);
      }, 4000);
    } else {
      clearInterval(heartbeatIntervalCache[userID]);
      heartbeatIntervalCache[userID] = setInterval(() => {
        if (!falg) {
          console.log('修改用户在线状态', userID);
          callback('logout', {
            userID
          })
          // 修改用户在线状态
          clearInterval(heartbeatIntervalCache[userID]);
          clearTimeout(heartbeatTimeoutCache[userID]);
          clearInterval(userlistIntervalCache[userID]);
        }
      }, 6000);
    }
    heartbeatTimeoutCache[userID] = setTimeout(() => {
      socket.emit('online', 1);
      falg = 0
    }, 2000);
  })
  socket.on('chat', (data) => {
    const { account, msg, time, type } = JSON.parse(data);
    console.log('====================socket MSG====================', msg, time, 'chat事件');
    if (socketPool[account] && socketPool[account].socket) {
      // 消息转发
      socketPool[account].socket.emit('receive', JSON.stringify({
        msg,
        from: userID,
        time,
        type
      }))
    }
  })
  userlistIntervalCache[userID] = setInterval(() => {
    callback('userlist', {
      socket
    })
  }, 2000);
}